//
//  GlobalMethod+Function.swift
//  全局方法 - 方法
//
//  Created by mini on 2025/4/28.
//

import Foundation
import Photos

private var loadingViewKey: UInt8 = 0

extension GlobalMethod {
    
    // MARK: - 认证跳转 - 下一步
    static func authNext(
        type: String,
        productCode: String,
        orderCode: String,
    ) {
        if isStr(type) {
            if type == "Chatterer" {
                // 认证 身份证+人脸
                HomeRequestApi.getUserIdentityInfoOneItem(productCode: productCode) { request, responseData in
                    // 先判断认证到什么步骤了。证件照 - 人脸 - 都已经完成
                    guard let res = responseData as? [String: Any] else {return}
                    if let model = ModelUserIdentityInfoOneItem.deserialize(from: res) {
                        if model.hate.darker != 1 {
                            // 证件照 未完成
                            let vc = ChooseIdCardTypeVC()
                            vc.productCode = productCode
                            vc.modelOneItem = model
                            GB_Nav?.pushViewController(vc, animated: true)
                        }
                        else {
                            // 证件照 已完成
                            // 判断人脸
                            if model.gnaw == 1 {
                                // 人脸 已完成
                                let vc = IdCardAuthSuccessVC()
                                vc.productCode = productCode
                                vc.name = model.hate.shavings.cautiously
                                vc.idCode = model.hate.shavings.half
                                vc.birth = model.hate.shavings.stubby
                                GB_Nav?.pushViewController(vc, animated: true)
                            }
                            else {
                                // 人脸 未完成
                                let vc = IdCardUploadVC()
                                vc.productCode = productCode
                                vc.navTitle = model.hate.rag
                                vc.isAuthFace = true
                                GB_Nav?.pushViewController(vc, animated: true)
                            }
                        }
                    }
                } failure: { request, error in
                    
                }
            }
            else if type == "Forest" {
                // 认证 个人信息
                let vc = AuthPersonalVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "Shadow" {
                // 认证 工作信息
                let vc = AuthWorkVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "minute" {
                // 认证 联系人
                let vc = AuthContactVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "peeked" {
                // 认证 银行卡
                let vc = AuthBankCardVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
        }
        else{
            // 下一步为空
            let startTime = GlobalMethod.getTimeStamp()
            HomeRequestApi.getJumpAddress(orderCode: orderCode) { request, responseData in
                let endTime = GlobalMethod.getTimeStamp()
                GlobalMethod.buryPoint(productCode: productCode, type: "9", startTime: startTime, endTime: endTime)
                guard let res = responseData as? [String: Any] else {return}
                if let model = ModelProductDetailFiercelyInfo.deserialize(from: res) {
                    let vc = BaseWebVC()
                    vc.webUrl = model.quiet
                    GB_Nav?.pushViewController(vc, animated: true)
                }
            } failure: { request, error in
                
            }
        }
    }
    
    // MARK: - 认证已完成 - 跳转
    static func authSuccess(
        type: String,
        productCode: String,
        orderCode: String,
    ) {
        if isStr(type) {
            if type == "Chatterer" {
                // 认证 身份证+人脸
                HomeRequestApi.getUserIdentityInfoOneItem(productCode: productCode) { request, responseData in
                    // 先判断认证到什么步骤了。证件照 - 人脸 - 都已经完成
                    guard let res = responseData as? [String: Any] else {return}
                    if let model = ModelUserIdentityInfoOneItem.deserialize(from: res) {
                        // 人脸 已完成
                        let vc = IdCardAuthSuccessVC()
                        vc.productCode = productCode
                        vc.name = model.hate.shavings.cautiously
                        vc.idCode = model.hate.shavings.half
                        vc.birth = model.hate.shavings.stubby
                        GB_Nav?.pushViewController(vc, animated: true)
                    }
                } failure: { request, error in
                    
                }
            }
            else if type == "Forest" {
                // 认证 个人信息
                let vc = AuthPersonalVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "Shadow" {
                // 认证 工作信息
                let vc = AuthWorkVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "minute" {
                // 认证 联系人
                let vc = AuthContactVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
            else if type == "peeked" {
                // 认证 银行卡
                let vc = AuthBankCardVC()
                vc.productCode = productCode;
                GB_Nav?.pushViewController(vc, animated: true)
            }
        }
        else{
            // 下一步为空
            let startTime = GlobalMethod.getTimeStamp()
            HomeRequestApi.getJumpAddress(orderCode: orderCode) { request, responseData in
                let endTime = GlobalMethod.getTimeStamp()
                GlobalMethod.buryPoint(productCode: productCode, type: "9", startTime: startTime, endTime: endTime)
                guard let res = responseData as? [String: Any] else {return}
                if let model = ModelProductDetailFiercelyInfo.deserialize(from: res) {
                    let vc = BaseWebVC()
                    vc.webUrl = model.quiet
                    GB_Nav?.pushViewController(vc, animated: true)
                }
            } failure: { request, error in
                
            }
        }
    }
    
    
    
    // MARK: - 获取混淆字段
    static func getConfusion(length: Int = 10) -> String {
        let letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return String((0..<length).compactMap { _ in letters.randomElement() })
    }
    
    // MARK: - 获取公共参数
    static func getCommonUrl() -> String {
        let tip = UnPackStr(GlobalMethod.getVersion)
        let touched = UnPackStr(GlobalMethod.getDeviceName)
        let minded = KeychainHelper.getIDFVFromKeychain()
        let sobbed = UIDevice.current.systemVersion
        let fight = "securreloanapi"
        let places = UnPackStr(GlobalData.sharedInstance.GB_SessionID)
        let slim = KeychainHelper.getIDFVFromKeychain()
        let boyfine = GlobalMethod.getConfusion()
        let str = "body=ios&tip=\(tip)&touched=\(touched)&minded=\(minded)&sobbed=\(sobbed)&fight=\(fight)&places=\(places)&slim=\(slim)&boyfine=\(boyfine)"
        return str
    }
    
    // MARK: - 获取时间戳
    static func getTimeStamp() -> String {
        let timeInterval = Date().timeIntervalSince1970
        return String(format: "%.0f", timeInterval)
    }
    static func getTimeStampMillisecond() -> String {
        let timeInterval = Date().timeIntervalSince1970 * 1000
        return String(format: "%.0f", timeInterval)
    }
    
    // MARK: - 用户详细行为埋点
    static func buryPoint(
        productCode: String,
        type: String,
        startTime: String,
        endTime: String
    ) {
        HomeRequestApi.buryPoint(productCode: productCode, type: type, startTime: startTime, endTime: endTime) { request, responseData in
            
        } failure: { request, error in
            
        }
    }
    
    // MARK: - 是否可以侧滑
    static func canLeftSlide() -> Bool {
        guard let nav = GB_Nav else { return false }
        if nav.viewControllers.count <= 1 {
            return false
        }
        for vc in nav.viewControllers {
            if vc is GuideVC {
                return false
            }
        }
        return true
    }

    // MARK: - 提示
    static func showAlert(strAlert: String, time: CGFloat = 1.0) {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            GlobalData.sharedInstance.GB_NoticeView.showNotice(strAlert, time: time, frame: UIScreen.main.bounds, viewShow: window)
        }
    }

    static func showAlertWaitLoading(strAlert: String) {
        if let window = WindowManager.shared.getCurrentWindow() {
            window.endEditing(true)
            GlobalData.sharedInstance.GB_NoticeView.showWaitLoadingNotice(strAlert, frame: UIScreen.main.bounds, viewShow: window)
        }
    }

    static func hideAlertWaitLoading() {
        GlobalData.sharedInstance.GB_NoticeView.hideWaitLoadingNotice()
    }

    // MARK: - 显示loadingView
    static var loadingView: LoadingView {
        if let view = objc_getAssociatedObject(self, &loadingViewKey) as? LoadingView {
            return view
        }
        let newView = LoadingView()
        newView.leftTop = XY(0, 0)
        objc_setAssociatedObject(self, &loadingViewKey, newView, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        return newView
    }

    static func showLoadingView() {
        let view = loadingView
        view.hideLoading()
        view.beginAnimate()
        GlobalMethod.addViewInWindow(view: view)
    }

    static func hideLoadingView() {
        let view = loadingView
        view.hideLoading()
    }

    // MARK: - 添加自定义View到window上
    static func addViewInWindow(view: UIView) {
        if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
           let window = windowScene.windows.first
        {
            GlobalMethod.mainQueueBlock {
                window.endEditing(true)
                window.addSubview(view)
            }
        }
    }

    // MARK: - 页面present弹出的VC
    // 默认弹出高度medium
    static func present(vc: UIViewController, isLarge: Bool = false, customHeight: CGFloat = 0.0) {
        let navigationController = UINavigationController(rootViewController: vc)
        if #available(iOS 15.0, *) {
            if let sheet = navigationController.presentationController as? UISheetPresentationController {
                if customHeight > 0 {
                    if #available(iOS 16.0, *) {
                        let customDetent = UISheetPresentationController.Detent.custom { _ in
                            customHeight
                        }
                        sheet.detents = [customDetent]
                    } else {
                        // Fallback on earlier versions
                    }
                } else {
                    sheet.detents = [isLarge ? .large() : .medium()] // 设置弹出视图的高度 .medium()
                }
                sheet.preferredCornerRadius = 24 // 设置圆角
                sheet.prefersGrabberVisible = true // 显示顶部的抓手
            }
        }
        // 获取当前最顶层的控制器来执行present
        if let topVC = GB_Nav?.topMostViewController() {
            topVC.present(navigationController, animated: true)
        } else {
            GB_Nav?.present(navigationController, animated: true)
        }
    }
    
    // MARK: - dismiss 返回
    static func dismiss(animated: Bool = true, completion: (() -> Void)? = nil) {
        if let topVC = GB_Nav?.topMostViewController() {
            topVC.dismiss(animated: animated, completion: completion)
        } else {
            GB_Nav?.dismiss(animated: animated, completion: completion)
        }
    }

    // MARK: - 当天只执行一次的方法
    static func shouldExecuteOnceToday(forKey key: String) -> Bool {
        let defaults = UserDefaults.standard
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = TIME_DAY_SHOW
        let today = dateFormatter.string(from: Date())
        // 获取上次执行的日期
        let lastExecuteDate = defaults.string(forKey: key)
        // 如果从未执行过或者不是今天执行的
        if lastExecuteDate != today {
            // 更新执行日期
            defaults.set(today, forKey: key)
            return true
        }
        return false
    }

    // MARK: - 动画 - 图片从左到右过渡动画显示
    static func setupMaskAnimation(view: UIView, _ duration: Double = 2.0) {
        let maskLayer = CAShapeLayer()
        // 设置遮罩层
        maskLayer.fillColor = UIColor.white.cgColor
        // 创建初始路径（空路径）
        let initialPath = UIBezierPath(rect: CGRect(
            x: 0,
            y: 0,
            width: 0,
            height: view.bounds.height
        ))
        // 创建最终路径
        let finalPath = UIBezierPath(rect: CGRect(
            x: 0,
            y: 0,
            width: view.bounds.width,
            height: view.bounds.height
        ))
        // 设置初始路径
        maskLayer.path = initialPath.cgPath
        // 将遮罩层应用到imageView
        view.layer.mask = maskLayer
        // 创建路径动画
        let animation = CABasicAnimation(keyPath: "path")
        animation.fromValue = initialPath.cgPath
        animation.toValue = finalPath.cgPath
        animation.duration = duration // 动画时间
        animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
        animation.isRemovedOnCompletion = false
        animation.fillMode = .forwards
        // 添加动画
        maskLayer.add(animation, forKey: "pathAnimation")
        // 设置最终路径
        maskLayer.path = finalPath.cgPath
    }
    
    
    
    // MARK: - 异步执行
    static func asyncBlock(_ block: @escaping () -> Void) {
        DispatchQueue.global(qos: .default).async(execute: block)
    }
    
    static func mainQueueBlock(_ block: @escaping () -> Void) {
        DispatchQueue.main.async(execute: block)
    }
}
